using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
using System.IO;

/// <summary>
/// Mesh Builder by @VildNinja
/// Visit www.vildninja.dk for more information.
/// 30/05/2013
/// 
/// The content of this file is in the public domain :)
/// </summary>
public class MeshBuilder : EditorWindow
{
	
	private Texture texture;
	private string name = "New Collision Mesh";
	private List<Vector3> vertex;
	private Mesh mesh;
	
	[MenuItem("Assets/Create/Mesh From Texture")]
	static void Init ()
	{
		MeshBuilder builder = (MeshBuilder) EditorWindow.GetWindow(typeof(MeshBuilder));
	}
	
	void OnGUI()
	{
		if (vertex == null)
			vertex = new List<Vector3>();
		texture = (Texture)EditorGUI.ObjectField(new Rect(5, 5, 50, 50), texture, typeof(Texture), true);
		name = EditorGUI.TextField(new Rect(60, 10, 160, 18), name);
		EditorGUI.LabelField(new Rect(225, 10, 150, 18), "Build meshes Clockwise!");
        if (texture != null)
        {
            if (vertex.Count > 0)
            {
                if (GUI.Button(new Rect(60, 32, 50, 18), "Undo"))
                {
                    vertex.RemoveAt(vertex.Count - 1);
                }

                if (GUI.Button(new Rect(115, 32, 50, 18), "Clear"))
                {
                    vertex.Clear();
                }
            }
            if (vertex.Count > 2)
            {
                if (GUI.Button(new Rect(170, 32, 50, 18), "Build"))
                {
                    BuildMesh();
                }
            }
            Rect preview;
            if (texture.width / texture.height > (position.width - 10) / (position.height - 70))
            {
                preview = new Rect(5, 65, position.width - 10, texture.height * ((position.width - 10) / texture.width));
            }
            else
            {
                preview = new Rect(5, 65, texture.width * ((position.height - 70) / texture.height), position.height - 70);
            }
            GUI.DrawTexture(preview, texture);

            if (Event.current.type == EventType.MouseDown)
            {
                Vector2 pos = new Vector3();
                pos.x = (Event.current.mousePosition.x - preview.x) / preview.width;
                pos.y = (Event.current.mousePosition.y - preview.y) / preview.width;
                Debug.Log("click " + Event.current.mousePosition + " -> " + pos);
                vertex.Add(pos);

                Repaint();
            }

            Vector3 last = Vector3.forward;
            foreach (var v in vertex)
            {
                Vector3 tmp = new Vector3();
                tmp.x = preview.x + v.x * preview.width;
                tmp.y = preview.y + v.y * preview.width;

                Handles.color = Color.cyan;
                Handles.DrawSolidDisc(tmp, Vector3.back, 3);

                if (last.z < 0.1)
                {
                    Handles.color = Color.green;
                    Handles.DrawLine(last, tmp);
                }
                else
                {
                    Handles.color = Color.gray;
                    last = new Vector3();
                    last.x = preview.x + vertex[vertex.Count - 1].x * preview.width;
                    last.y = preview.y + vertex[vertex.Count - 1].y * preview.width;
                    Handles.DrawLine(last, tmp);
                }

                last = tmp;
            }
        }
        else
        {
            EditorGUI.LabelField(new Rect(5, 65, position.width - 10, position.height - 75), "Mesh Builder by @VildNinja\nSelect a texture to get started!");
        }
	}
	
	private void BuildMesh()
	{
		mesh = new Mesh();
		Vector3[] vertices = new Vector3[vertex.Count * 2];
		int[] tris = new int[vertex.Count * 6];
		for (int i = 0; i < vertex.Count; i++)
		{
			vertices[i * 2] = new Vector3(vertex[i].x - .5f, 1 - vertex[i].y - .5f, -.5f);
			vertices[i * 2 + 1] = new Vector3(vertex[i].x - .5f, 1 - vertex[i].y - .5f, .5f);
			
			tris[i * 6] = i * 2;
			tris[i * 6 + 1] = i * 2 + 1;
			tris[i * 6 + 2] = ((i + 1) % vertex.Count) * 2;
			tris[i * 6 + 3] = ((i + 1) % vertex.Count) * 2;
			tris[i * 6 + 4] = i * 2 + 1;
			tris[i * 6 + 5] = ((i + 1) % vertex.Count) * 2 + 1;
		}
		
		mesh.vertices = vertices;
		mesh.triangles = tris;

        string path = AssetDatabase.GetAssetPath(UnityEditor.Selection.activeObject);
		if (path == "")
		{
		    path = "Assets";
		}
		else if (Path.GetExtension(path) != "")
		{
            path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(UnityEditor.Selection.activeObject)), "");
		}

		AssetDatabase.CreateAsset(mesh, AssetDatabase.GenerateUniqueAssetPath (path + "/" + name + ".asset"));
	}
}
